package com.zmj.framework.util;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.framework.request.PageParam;
import com.zmj.framework.request.SortItem;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PageUtil {

    public static <T> Page<T> buildPage(PageParam pageParam) {
        return buildPage(pageParam, null, null);
    }

    /**
     * @param pageParam
     * @param sortItems
     * @param filter    对前端传入的排序字段进行过滤，防止SQL注入
     * @return {@link Page}<{@link T}>
     */
    public static <T> Page<T> buildPage(PageParam pageParam, Collection<SortItem> sortItems, Predicate<? super SortItem> filter) {
        Page<T> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        if (CollectionUtils.isNotEmpty(sortItems) && filter != null) {
            page.addOrder(sortItems.stream().filter(filter).map(sortItem -> SortItem.ORDER_ASC.equalsIgnoreCase(sortItem.getOrder()) ?
                            OrderItem.asc(sortItem.getField()) : OrderItem.desc(sortItem.getField()))
                    .collect(Collectors.toList()));
        }
        return page;
    }
}